/** 
 * All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
 * 
 *BaseTeamInfoController
 * 团队信息
 * 
 * 修改纪录
 * 2020-08-27 版本：1.0 jiangtao 创建。
 * @version 版本：1.0
 * @author 作者：jiangtao
 * 创建日期：2020-08-27
 */

package com.topscomm.base.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.topscomm.base.BaseSystemConst;
import com.topscomm.base.controller.auto.BaseTeamInfoControllerAuto;
import com.topscomm.base.pojo.BaseTeamInfoEntity;
import com.topscomm.base.pojo.BaseTeamRelationEntity;
import com.topscomm.base.service.impl.BaseCboUserExtendService;
import com.topscomm.base.service.impl.BaseTeamInfoService;
import com.topscomm.base.service.impl.BaseTeamRelationService;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;

/**
 * @author: jiangtao
 * @date: 2020-08-27
 * @description:团队信息Controller
 * @modify:
 */
@RestController
@RequestMapping("base/teamInfo")
public class BaseTeamInfoController extends BaseTeamInfoControllerAuto implements IBaseTeamInfoController {
	/**
	 * @author: jiangtao
	 * @date: 2020-08-27
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		// 查询当前登录用户担任秘书的团队信息
		if (paraMap.containsKey("qry_visible")) {
			String value = paraMap.get("qry_visible").toString();
			if (!StringUtil.isEmpty(value)) {
				sql.appendSingle(
						" exists ( select u.teamid from BASETEAMUSER u where BASETEAMINFO.id = u.TEAMID AND u.USERCODE = '{0}' AND u.USERTYPE = '{1}')",
						getUserBean().getUser().getCode(), BaseSystemConst.TeamUserTypeEnum.Secretary);
			}
		}
		if (sql.length() == 0) {
			sql.appendSingle(" 1=1 ");
		}
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_idlist")) {
			String value = paraMap.get("qry_idlist").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and id in ({0}) ", value);
		}
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and code = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_type")) {
			String value = paraMap.get("qry_type").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and type = '{0}' ", value);
		}
		if (paraMap.containsKey("whereSql")) {
			String value = paraMap.get("whereSql").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and  {0} ", value);
		}
		return sql.toString();
	}

	/**
	 * @author: jiangtao
	 * @date: 2020-08-27
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/**
	 * 保存函数
	 * 
	 * @author: jiangtao
	 * @date: 2020年8月26日上午9:44:03
	 * @params:
	 * @return_type: ResponseResult<Object>
	 * @description:
	 * @modify:
	 */
	@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }, value = "doSave")
	public ResponseResult<Object> doSave(@RequestBody(required = false) Map<String, Object> map) {
		try {
			Map<String, Object> resultMap = this.service.doSave(map);
			return ResponseResult.ok(resultMap);
		} catch (Exception e) {
			return ResponseResult.error(e.getMessage());
		}
	}

	/**
	 * 加载数据展示直接上下级团队
	 * 
	 * @author: jiangtao
	 * @date: 2020年8月26日上午9:44:28
	 * @params:
	 * @return_type:
	 * @description:
	 * @modify:
	 */
	@Override
	protected void afterLoad(Map<String, Object> paraMap) {
		super.afterLoad(paraMap);
		long id = ConvertUtil.convertToLong(paraMap.get("id"));
		if (id >= 0) {
			BaseTeamRelationService baseTeamRelationService = (BaseTeamRelationService) SpringUtil
					.getBean("baseTeamRelationService");
			StringBufferProxy sql = new StringBufferProxy();
			String highteamIds = "";
			String highteamNames = "";
			String lowteamIds = "";
			String lowteamNames = "";
			// 查询对应的上级团队id
			sql.appendSingle("subteamid = {0}", id);
			List<BaseTeamRelationEntity> baseTeamRelationEntities = baseTeamRelationService
					.queryByWhere(sql.toString());
			if (baseTeamRelationEntities != null && baseTeamRelationEntities.size() > 0) {
				for (BaseTeamRelationEntity relationEntity : baseTeamRelationEntities) {
					highteamIds += relationEntity.getTeamid();
					highteamIds += ",";
				}
			}
			if (!StringUtil.isEmpty(highteamIds)) {
				highteamIds = highteamIds.substring(0, highteamIds.length() - 1);
				sql.clear();
				sql.appendSingle(" id in ({0})", highteamIds);
				List<BaseTeamInfoEntity> baseTeamInfoEntities = this.service.queryByWhere(sql.toString());
				for (BaseTeamInfoEntity teamInfoEntity : baseTeamInfoEntities) {
					highteamNames += teamInfoEntity.getName();
					highteamNames += ",";
				}
				if (!StringUtil.isEmpty(highteamNames)) {
					highteamNames = highteamNames.substring(0, highteamNames.length() - 1);
				}
			}
			// 查询对应下级团队的id
			sql.clear();
			sql.appendSingle("teamid = {0}", id);
			baseTeamRelationEntities = baseTeamRelationService.queryByWhere(sql.toString());
			if (baseTeamRelationEntities != null && baseTeamRelationEntities.size() > 0) {
				for (BaseTeamRelationEntity relationEntity : baseTeamRelationEntities) {
					lowteamIds += relationEntity.getSubteamid();
					lowteamIds += ",";
				}
			}
			if (!StringUtil.isEmpty(lowteamIds)) {
				lowteamIds = lowteamIds.substring(0, lowteamIds.length() - 1);
				sql.clear();
				sql.appendSingle(" id in ({0})", lowteamIds);
				List<BaseTeamInfoEntity> baseTeamInfoEntities = this.service.queryByWhere(sql.toString());
				for (BaseTeamInfoEntity teamInfoEntity : baseTeamInfoEntities) {
					lowteamNames += teamInfoEntity.getName();
					lowteamNames += ",";
				}
				if (!StringUtil.isEmpty(lowteamNames)) {
					lowteamNames = lowteamNames.substring(0, lowteamNames.length() - 1);
				}
			}
			if (!StringUtil.isEmpty(highteamIds)) {
				paraMap.put("highteam", highteamIds);
				paraMap.put("disphighteam", highteamNames);
			}
			if (!StringUtil.isEmpty(lowteamIds)) {
				paraMap.put("lowteam", lowteamIds);
				paraMap.put("displowteam", lowteamNames);
			}
		}
	}

	@GetMapping(value = "/serachRelateUser")
	public ResponseResult<Object> serachRelateUser(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			BaseCboUserExtendService baseCboUserExtendService = (BaseCboUserExtendService) SpringUtil
					.getBean("baseCboUserExtendService");
			BaseTeamInfoService baseTeamInfoService = (BaseTeamInfoService) SpringUtil.getBean("baseTeamInfoService");
			List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
			List<String> userCodeList = new ArrayList<String>();
			List<String> userNameList = new ArrayList<String>();
			if (paraMap.containsKey("sharedeptcodes")) {
				String sharedeptcodes = ConvertUtil.convertToString(paraMap.get("sharedeptcodes"));
				if (!StringUtil.isEmpty(sharedeptcodes)) {
					List<Map<String, Object>> userList = baseCboUserExtendService
							.searchUsersByDeptCodes(sharedeptcodes);
					for (Map<String, Object> map : userList) {
						map.put("usercode", map.remove("code"));
						map.put("username", map.remove("name"));
					}
					resultList.addAll(userList);
				}
			}
			if (paraMap.containsKey("shareroleids")) {
				String shareroleids = ConvertUtil.convertToString(paraMap.get("shareroleids"));
				if (!StringUtil.isEmpty(shareroleids)) {
					List<Map<String, Object>> userList = baseCboUserExtendService.searchUserByRoleIds(shareroleids);
					for (Map<String, Object> map : userList) {
						map.put("usercode", map.remove("code"));
						map.put("username", map.remove("name"));
					}
					resultList.addAll(userList);
				}
			}
			if (paraMap.containsKey("shareteamids")) {
				String shareteamids = ConvertUtil.convertToString(paraMap.get("shareteamids"));
				if (!StringUtil.isEmpty(shareteamids)) {
					List<Map<String, Object>> userList = baseTeamInfoService.getTeamMembers(shareteamids);
					resultList.addAll(userList);
				}
			}
			if (paraMap.containsKey("shareusercodes")) {
				String shareusercodes = ConvertUtil.convertToString(paraMap.get("shareusercodes"));
				if (!StringUtil.isEmpty(shareusercodes)) {
					String[] users = shareusercodes.split(",");
					String tempuserCodes = "";
					for (String code : users) {
						tempuserCodes = tempuserCodes + "'" + code + "'" + ",";
					}
					if (tempuserCodes.length() > 0) {
						shareusercodes = tempuserCodes.substring(0, tempuserCodes.length() - 1);
					}

					StringBufferProxy sql = new StringBufferProxy();
					sql.appendSingle("select code as usercode, name as username from CboUser where code in ({0})",
							shareusercodes);
					List<Map<String, Object>> userList = this.service.selectExecute(sql.toString());
					resultList.addAll(userList);
				}
			}
			userCodeList = resultList.stream().map(userMap -> ConvertUtil.convertToString(userMap.get("usercode")))
					.distinct().collect(Collectors.toList());
			userNameList = resultList.stream().map(userMap -> ConvertUtil.convertToString(userMap.get("username")))
					.distinct().collect(Collectors.toList());
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("usercode", userCodeList);
			result.put("username", userNameList);
			return ResponseResult.ok(result);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}
}
